argss <- commandArgs(trailingOnly = TRUE)

print(argss)

name <- argss[2]

names=read.table(name, col.names=c("file", "legend", "win", "sample"), stringsAsFactors=F)
print(names)

names=names[order(names$win),]



xlim=c(0, 1)
ylim=xlim
hlineby=.1
hline=seq((ylim[1]+hlineby), (ylim[2]-hlineby), hlineby)
vline=hline


pdf("lorenz.pdf", width=9, height=9)

par(ann=F, xaxs='i', yaxs='i')

# plot(NA, type='n', xlim=xlim, ylim=ylim, cex.axis=.5)
plot(NA, type='n', xlim=xlim, ylim=ylim)
# abline(0,1, col='black')

abline(v=vline, h=hline, lty=3, col='gray')

title_main=paste("Lorenz curves for sample ", names$sample[1])

title(main=title_main, xlab="Cumulative fraction of genome", ylab="Cumulative fraction of total reads")

names$color=rainbow(nrow(names))

max_num=10000

simu=runif(max_num)
num_sub=round(max_num/10)
count=hist(simu, breaks=num_sub, plot=F)$counts
rc=sort(count)
rc=c(0, rc)
num_sub=num_sub+1 # start from (0,0)
x=seq(from=0, to=1, length.out=num_sub)
sum=sum(rc)
rc_norm=NULL
for (ii in 1:num_sub) {
	rc_norm[ii]=sum(rc[1:ii]) / sum
}

# gini_simu=1-((2*sum(rc_norm)-rc_norm[1]-rc_norm[num_sub])/(num_sub-1))
# gini_simu_str=paste('simu', sprintf("%.4f", gini_simu), sep=' ')

# perfect_str=paste('Perfect', sprintf("%d", 0), sep=' ')

# lines(x, rc_norm, col='gray')

lines(c(0,1), c(0,1), col='black')

gini_str=vector('character')

for (i in 1:nrow(names)) {
	rc0=read.table(names[i,1])
	if (max_num < nrow(rc0)) {
		rc=sample(rc0$V1, max_num)
		len=max_num
	}else {
		rc=rc0$V1
		len=length(rc)
	}
	
	rc=sort(rc)
	
	sum=sum(rc)
	rc_norm=NULL
	for (ii in 1:len) {
		rc_norm[ii]=sum(rc[1:ii]) / sum
	}
	x=seq(from=0, to=1, length.out=len)
	lines(x, rc_norm, col=names$color[i])
	
	gini=1-((2*sum(rc_norm)-rc_norm[1]-rc_norm[len])/(len-1))
	gini_str[i]=paste(names$legend[i], sprintf("%.3f", gini), sep=' ')
	
}

legend("topleft", inset=.05, lty=c(1,1,1), c(names$legend, 'Perfect'), col=c(names$color, 'black'))

dev.off()


